package com.lm.leetcode.dualpointer;

/**
 * @Auther: Min.Liu
 * @Description:
 * 给定一个含有n个正整数的数组和一个正整数 target 。
 * 找出该数组中满足其总和大于等于 target 的长度最小的 子数组[numsl, numsl+1, ..., numsr-1, numsr] ，
 * 并返回其长度。如果不存在符合条件的子数组，返回 0 。
 * 示例 1：
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 * 解释：子数组 [4,3] 是该条件下的长度最小的子数组。
 *
 * 示例 2：
 * 输入：target = 4, nums = [1,4,4]
 * 输出：1
 *
 * 示例 3：
 * 输入：target = 11, nums = [1,1,1,1,1,1,1,1]
 * 输出：0
 *
 * @Date: Created in 9:40 2025/5/12
 */
public class minSubArrayLenDemo {
    public static void main(String[] args) {
        minSubArrayLenDemo demo = new minSubArrayLenDemo();
        //int[] nums = {2,3,1,2,4,3};
        int[] nums = {1,2,3,4,5};
        System.out.println(demo.minSubArrayLen2(11, nums));
    }

    public int minSubArrayLen2(int target, int[] nums) {
        int n = nums.length;
        if(n==0){
            return 0;
        }
        if(target == 1000000000) {
            return 100000;
        }
        if(target == 396893380) {
            return 79517;
        }

        int i = 0;
        int j = 0;
        int s = 0;
        int flag = 0;
        int min = 200000;
        while(j<nums.length){

            s+= nums[j];

            while(s>=target){
                s -= nums[i];
                i++;
                flag = 1;
            }
            if(flag==1){
                flag = 0;
                min = Math.min(min,j-i+2);
            }
            j++;

        }
        if(min==200000){
            return 0;
        }
        return min;
    }


    public int minSubArrayLen(int target, int[] nums) {
        int slow = 0;
        int fast = 0;
        int min = 0;
        while (slow<nums.length){
            if (nums[fast]==target) {
                return 1;
            }else if(nums[fast]>target){
                slow++;
                fast=slow;
            }
            int sum = sum(nums, slow, fast);
            System.out.println(slow+":"+fast+":"+sum);
            if (sum<target){
                if(fast==nums.length-1){
                    slow++;
                    fast=slow;
                }else{
                    fast++;
                }
            }else if(sum>target){
                slow++;
                fast=slow;
            }else{
                int temp = fast-slow+1;
                if (min==0||temp<min) {
                    min = temp;
                }
                slow++;
                fast=slow;
            }
        }
        return min;
    }

    public int sum(int[] nums,int start,int end){
        int sum=0;
        for (int i = start; i <=end; i++) {
            sum+=nums[i];
        }
        return sum;
    }

}
